package org.yan.stock.server.core;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.yan.stock.server.client.Client;
import org.yan.stock.server.client.ClientRegistry;
import org.yan.stock.server.client.ClientServiceFactory;

@SuppressWarnings("serial")
public class StsvrServlet extends HttpServlet {
	
	/*
	 * Get the max client number, the min threshold to send notification, the refresh rate of  client list;
	 * then init the client registry and resource controller.
	 */
	public void init() throws ServletException {
		super.init();
		
		int threshold = Integer.valueOf(this.getServletConfig().getInitParameter("maxClient"));
		List<Client> clientList = ClientServiceFactory.getClientService().fetchClientList(threshold);
		ClientRegistry.getRegistry().init(clientList, threshold);

		double minValue = Double.valueOf(this.getServletConfig().getInitParameter("minValue"));
		int refreshRate = Integer.valueOf(this.getServletConfig().getInitParameter("refreshRate"));
		new ResourceController(minValue, refreshRate).start();
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		Client client = handleRequest(req);
		ClientServiceFactory.getClientService().merge(client);
	}
	
	/**
	 * Get Client Info From Request
	 * @param req
	 * @return
	 */
	private Client handleRequest(HttpServletRequest req) {
		Client client = new Client();
		client.setAuthId(req.getParameter("devregid"));
		client.setSenderId(req.getParameter("mail"));
		client.setOs(req.getParameter("os"));
		client.setStocks(req.getParameter("stocks"));
		client.setLatchs(req.getParameter("latchs"));
		if("".equals(client.getLatchs().replace(",","").replace("0", ""))) {
			client.setPaidType("0");
		}
		else {
			client.setPaidType("1");
		}
		return client;
	}
	
}
